package com.sea.physical.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.util.PhysicalStatusEnum;
import com.sea.finance.entity.Vt;
import com.sea.operate.entity.RelatedSku;
import com.sea.operate.service.RelatedSkuService;
import com.sea.physical.entity.CreatePlan;
import com.sea.physical.entity.CreateSku;
import com.sea.physical.service.CabinetService;
import com.sea.physical.service.CreatePlanService;
import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.sea.physical.service.CreateSkuService;
import com.sea.product.service.ChannelService;
import com.sea.product.service.ProductService;
import com.sea.supply.entity.Buy;
import com.sea.supply.service.SupplierService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 创建发运计划明细
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/physical/createSku")
public class CreateSkuController {

    @Autowired
    private CreatePlanService createPlanService;
    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private CabinetService cabinetService;
    @Autowired
    private CreateSkuService createSkuService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ProductService productService;


    /**
     * 新增页面
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model,@RequestParam("createId")Integer id) {
        getModel(model);
        model.addAttribute("createId",id);
        return "/sea/physical/createSku/add";
    }
    /**
     * 新增页面
     * @param model
     * @return
     */
    @RequestMapping("/editpage")
    public String editpage(Model model,@RequestParam("id")Integer id) {
        getModel(model);
        model.addAttribute("createPlan",createPlanService.findById(id));
        return "/bbpk/physical/createPlan/edit";
    }

    /**
     * 新增SKU明细
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/addSkuPage")
    public String addSkuPage(Model model,@RequestParam("id")Integer id){
        getModel(model);
        model.addAttribute("createId",id);
        return "/sea/physical/createPlan/addSku";
    }

    @RequestMapping("/editSkuPage")
    public String editSkuPage(Model model,@RequestParam("id")Integer id){
        getModel(model);
        CreateSku createSku = createSkuService.findById(id);
        model.addAttribute("createSku",createSku);
        model.addAttribute("product",productService.findBySku(createSku.getCreateSku()));
        return "/sea/physical/createSku/edit";
    }

    private void getModel(Model model){
        //国家字典
        model.addAttribute("supplier",supplierService.findByCnd(null));
        //柜型
        model.addAttribute("channel",channelService.findByCnd(null));
        //仓库
        model.addAttribute("ware",dictDetailService.findByTypeCode("base_ware",null));
    }

    @RequestMapping("/findByCreateId")
    @ResponseBody
    public List<CreateSku> findByCreateId(Integer createId){
        return createSkuService.findByCreateId(createId);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(@RequestParam("id") Integer id,@RequestParam("createId")Integer createId) {
        AjaxReturn result = Ajax.fail().setMsg("删除失败！");
        try{
            if (null != id && createSkuService.delete(id,createId) > 0) {
                result.setOk(true).setMsg("删除成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importSku(Model model,
                                MultipartFile importSession,
                                @RequestParam("createId")Integer createId) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == importSession || importSession.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = importSession.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                InputStream is = importSession.getInputStream();
                createSkuService.importSku(is,fileName,createId);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }



    @RequestMapping("/importCreatePlan")
    @ResponseBody
    public AjaxReturn importCreatePlan(Model model,
                                MultipartFile importSession2) {
        AjaxReturn result = Ajax.fail().setMsg("上传失败！");
        try {
            if (null == importSession2 || importSession2.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = importSession2.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                InputStream is = importSession2.getInputStream();
                createSkuService.importCreatePlan(is,fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        }catch (DuplicateKeyException e) {

            result.setMsg("柜号存在重复,请重新添加!");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping("/importCreateSku")
    @ResponseBody
    public AjaxReturn importCreateSku(Model model,
                                       MultipartFile importSession3) {
        AjaxReturn result = Ajax.fail().setMsg("上传失败1！");
        try {
            if (null == importSession3 || importSession3.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = importSession3.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                InputStream is = importSession3.getInputStream();
                createSkuService.importCreateSku(is,fileName);
                result.setOk(true);
                result.setMsg("上传成功1！！");
            }
        }catch (DuplicateKeyException e) {

            result.setMsg("柜号存在重复,请重新添加!");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 保存
     * @param createSku
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(CreateSku createSku) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != createSku && createSkuService.save(createSku) > 0) {
                createPlanService.updateTotal(createSku.getCreateId());
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(CreateSku createSku) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            CreatePlan createPlan = createPlanService.findById(createSku.getCreateId());
            if(createPlan.getCreatePlanStatus().equals(2)){
                result.setMsg("请先取消分配再修改数量!");
                return result;
            }
            if (null != createSku && createSkuService.usave(createSku) > 0) {
                createPlanService.updateTotal(createSku.getCreateId());
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    /**
     * 导出当前数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletResponse response, @RequestParam("ids") Integer ids[]) throws IOException {
        List<CreateSku> skuList=new ArrayList<>();
        skuList=createSkuService.exportByCreateId(ids);

        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("发运计划明细", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 自定义表头顺序（按需要的顺序排列）
        List<List<String>> customHead = new ArrayList<>();
        customHead.add(Arrays.asList("柜号"));
        customHead.add(Arrays.asList("装柜时间"));
        customHead.add(Arrays.asList("shipment ID"));
        customHead.add(Arrays.asList("渠道"));
        customHead.add(Arrays.asList("SKU"));
        customHead.add(Arrays.asList("产品名称"));
        customHead.add(Arrays.asList("颜色"));
        customHead.add(Arrays.asList("尺码(CM)"));
        customHead.add(Arrays.asList("尺码(INCH)"));
        customHead.add(Arrays.asList("FNSKU"));
        customHead.add(Arrays.asList("Listing"));
        customHead.add(Arrays.asList("数量"));
        customHead.add(Arrays.asList("总件数"));
        customHead.add(Arrays.asList("装箱量"));
        customHead.add(Arrays.asList("箱数"));
        customHead.add(Arrays.asList("供应商"));
        customHead.add(Arrays.asList("总毛重"));
        customHead.add(Arrays.asList("总净重"));
        customHead.add(Arrays.asList("总体积"));
        customHead.add(Arrays.asList("备注"));
        customHead.add(Arrays.asList("柜型"));
        customHead.add(Arrays.asList("运输方式"));
        customHead.add(Arrays.asList("国家"));
        customHead.add(Arrays.asList("装柜地点"));
        customHead.add(Arrays.asList("仓库"));
        customHead.add(Arrays.asList("状态"));

        // 3. 导出Excel
        EasyExcel.write(response.getOutputStream(), Buy.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("发运计划明细")
                .head(customHead)  // 设置自定义表头
                .doWrite(convertDataToCustomOrder2(skuList)); // 转换数据顺序
    }

    /**
     * 将原始数据转换为与自定义表头匹配的顺序
     */
    private List<List<Object>> convertDataToCustomOrder2(List<CreateSku> dataList) {
        List<List<Object>> result = new ArrayList<>();
        for (CreateSku vt : dataList) {
            List<Object> row = new ArrayList<>();
            row.add(vt.getCreatePlanNo());
            row.add(vt.getCreatePlanPlaceDate());
            row.add(vt.getCreateShipmentId());
            row.add(vt.getCreateChannelName());
            row.add(vt.getCreateSku());
            row.add(vt.getProductName());
            row.add(vt.getProductColorName());
            row.add(vt.getProductCm());
            row.add(vt.getProductInch());
            row.add(vt.getCreateFnSku());
            row.add(vt.getCreateListing());
            row.add(vt.getCreateNumber());
            row.add(vt.getCreateNumberTotal());
            row.add(vt.getCreatePackage());
            row.add(vt.getCreateBoxNumber());
            row.add(vt.getCreateSupplierName());
            row.add(vt.getCreateWeightTotal());
            row.add(vt.getCreateKgTotal());
            row.add(vt.getCreateVolumeTotal());
            row.add(vt.getCreateRemark());
            row.add(vt.getCreatePlanCabinetName());
            row.add(vt.getTransportName());
            row.add(vt.getCountryName());
            row.add(vt.getCreatePlanPlace());
            row.add(vt.getCreateWareName() == null?"":vt.getCreateWareName());
            row.add(PhysicalStatusEnum.getStatusName(Integer.parseInt(vt.getCreatePlanStatus())));
            result.add(row);
        }
        return result;
    }



    @ResponseBody
    @RequestMapping(value = "/exportDeclaration", method = RequestMethod.GET)
    public void testProduce(@RequestParam("createId")Integer createId,
                            HttpServletResponse response) throws IOException {
        List<CreateSku> list = createSkuService.exportDeclarationByCreateId(createId);
        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("报关单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 自定义表头顺序（按需要的顺序排列）
        List<List<String>> customHead = new ArrayList<>();
        customHead.add(Arrays.asList("SKU"));
        customHead.add(Arrays.asList("Shipment ID"));
        customHead.add(Arrays.asList("Amazon Reference ID"));
        customHead.add(Arrays.asList("ASIN"));
        customHead.add(Arrays.asList("品名"));
        customHead.add(Arrays.asList("中文品名"));
        customHead.add(Arrays.asList("清关编码"));
        customHead.add(Arrays.asList("成分"));
        customHead.add(Arrays.asList("商品名称"));
        customHead.add(Arrays.asList("尺码"));
        customHead.add(Arrays.asList("颜色"));
        customHead.add(Arrays.asList("可发货数量"));
        customHead.add(Arrays.asList("装箱量"));
        customHead.add(Arrays.asList("外箱长"));
        customHead.add(Arrays.asList("外箱宽"));
        customHead.add(Arrays.asList("外箱高"));
        customHead.add(Arrays.asList("单箱体积"));
        customHead.add(Arrays.asList("实际箱数"));
        customHead.add(Arrays.asList("单箱毛重"));
        customHead.add(Arrays.asList("总毛重"));
        customHead.add(Arrays.asList("总净重"));
        customHead.add(Arrays.asList("总体积"));
        customHead.add(Arrays.asList("目的仓"));
        // 3. 导出Excel
        EasyExcel.write(response.getOutputStream(), Buy.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("采购订单")
                .head(customHead)  // 设置自定义表头
                .doWrite(convertDataToCustomOrder(list)); // 转换数据顺序
    }

    /**
     * 将原始数据转换为与自定义表头匹配的顺序
     */
    private List<List<Object>> convertDataToCustomOrder(List<CreateSku> dataList) {
        List<List<Object>> result = new ArrayList<>();
        for (CreateSku createSku : dataList) {
            List<Object> row = new ArrayList<>();
            row.add(createSku.getCreateSku());
            row.add(createSku.getCreateShipmentId());
            row.add(createSku.getCreatePlanReferenceId());
            row.add(createSku.getAsin());
            row.add(createSku.getProductEnName());
            row.add(createSku.getProductDeclarationName());
            row.add(createSku.getProductCode());
            row.add(createSku.getProductComposition());
            row.add(createSku.getProductName());
            row.add(createSku.getProductSizeName());
            row.add(createSku.getProductColorName());
            row.add(createSku.getCreateNumber());
            row.add(createSku.getCreatePackage());
            row.add(createSku.getProductOutBoxLength());
            row.add(createSku.getProductOutBoxWidth());
            row.add(createSku.getProductOutBoxHeight());
            row.add(createSku.getCreateVolume());
            row.add(createSku.getCreateBoxNumber());
            row.add(createSku.getCreateWeight());
            row.add(createSku.getCreateWeightTotal());
            row.add(createSku.getCreateKgTotal());
            row.add(createSku.getCreateVolumeTotal());
            row.add(createSku.getCreateWareName());
            result.add(row);
        }
        return result;
    }
}
